package com.woniu.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniu.exception.LXLGException;
import com.woniu.product.client.param.AddSkuParam;
import com.woniu.product.common.ProductResultCode;
import com.woniu.product.infra.mapper.PropValueMapper;
import com.woniu.product.infra.model.*;
import com.woniu.product.infra.mapper.SkuMapper;
import com.woniu.product.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.product.service.dto.ProductItemDto;
import com.woniu.product.service.dto.SkuCanUseCouponDto;
import com.woniu.product.service.form.DeductStockServiceParam;
import com.woniu.product.service.form.RestoreStockServiceParam;
import com.woniu.result.Result;
import com.woniu.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonMultiLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import com.google.common.base.Joiner;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 库存量单位 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2022-11-26
 */
@Service
@Slf4j
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    @Resource
    private SpuService spuService;

    @Resource
    private SkuPropValueService skuPropValueService;

    @Resource
    private PropValueMapper propValueMapper;
    @Resource
    private RedissonClient redissonClient;


    @Override
    public void deductStock(DeductStockServiceParam deductStockServiceParam) throws InterruptedException {
        //加锁 锁名字包含商品ID
        RLock lock = redissonClient.getLock("lxlg:product:deduct:lock:" + deductStockServiceParam.getProductId());
        RedissonMultiLock redissonMultiLock = new RedissonMultiLock(lock);
        Boolean b = false;
        try {
            b = redissonMultiLock.tryLock(20, 20, TimeUnit.SECONDS);
            if (b) {
                Sku sku = getById(deductStockServiceParam.getProductId());
                UpdateWrapper<Sku> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("stock", sku.getStock() - deductStockServiceParam.getQuantity());
                updateWrapper.eq("sku_id", deductStockServiceParam.getProductId());
                update(updateWrapper);
            }
            //解锁
        } finally {
            if (redissonMultiLock != null) redissonMultiLock.unlock();
        }
    }

    @Override
    public void restoreStock(RestoreStockServiceParam restoreStockServiceParam) throws InterruptedException {
        //加锁 锁名字包含商品ID
        RLock lock = redissonClient.getLock("lxlg:product:restore:lock:" + restoreStockServiceParam.getProductId());
        RedissonMultiLock redissonMultiLock = new RedissonMultiLock(lock);
        Boolean b = false;
        try {
            b = redissonMultiLock.tryLock(20, 20, TimeUnit.SECONDS);
            if (b) {
                Sku sku = getById(restoreStockServiceParam.getProductId());
                UpdateWrapper<Sku> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("stock", sku.getStock() + restoreStockServiceParam.getQuantity());
                updateWrapper.eq("sku_id", restoreStockServiceParam.getProductId());
                update(updateWrapper);
            }
            //解锁
        } finally {
            if (redissonMultiLock != null) redissonMultiLock.unlock();
        }
    }

    /**
     * 根据skuId查询商品信息
     *
     * @param skuId
     * @return
     */
    @Override
    public ProductItemDto queryProductItem(Integer skuId) {
        ProductItemDto productItemDto = new ProductItemDto();
        Sku sku = getById(skuId);
        if (sku == null) {
            throw new LXLGException(ProductResultCode.SKU_INEXISTENCE);
        }
        Spu spu = spuService.getById(sku.getSpuId());
        if (spu == null) {
            throw new LXLGException(ProductResultCode.SPU_INEXISTENCE);
        }
        productItemDto.setSkuId(skuId);
        productItemDto.setPrice(sku.getPrice());
        productItemDto.setSpuName(spu.getSpuName());
        productItemDto.setSpuMainPic(spu.getSpuMainPic());
        //查询sku的属性
        QueryWrapper<SkuPropValue> qw = new QueryWrapper<>();
        qw.eq("sku_id", skuId);
        List<SkuPropValue> skuPropValues = skuPropValueService.list(qw);
        List<String> propValues = new ArrayList<>();
        List<Integer> skuValuesIds = new ArrayList<>();
        for (SkuPropValue skuPropValue : skuPropValues) {
            skuValuesIds.add(skuPropValue.getPropValueId());
        }
        if (skuValuesIds == null) {
            throw new LXLGException(ProductResultCode.PROPVALUE_NOT_FOUND);
        }
        List<PropValue> propValues1 = propValueMapper.selectBatchIds(skuValuesIds);

        for (PropValue propValue : propValues1) {
            propValues.add(propValue.getPropValueName());
        }
        productItemDto.setPropValues(propValues);
        return productItemDto;
    }

    @Override
    public void addSku(AddSkuParam addSkuParam) {
        Sku sku = BeanUtil.copyProperties(addSkuParam, Sku.class);
        List<Integer> propValueIds = addSkuParam.getPropValueIds();
        List<PropValue> propValues = propValueMapper.selectBatchIds(propValueIds);
        List<String> collect = propValues.stream().map(PropValue::getPropValueName).collect(Collectors.toList());

        //用-连接
        String skucode = Joiner.on('-').join(collect);
        Spu spu = spuService.getById(addSkuParam.getSpuId());
        skucode = skucode + "-" + spu.getSpuName();
        sku.setSkuCode(skucode);
        sku.setCreateTime(DateUtil.parseDateLong());
        sku.setSkuStatus("ON_SALE");
        save(sku);
        List<Integer> skupropValueIds = addSkuParam.getPropValueIds();
        String code = new String();

        Collections.sort(propValueIds);
        String skuQuerycode = Joiner.on('-').join(propValueIds);
        for (Integer propValueId :skupropValueIds) {
            SkuPropValue skuPropValue = new SkuPropValue();
            skuPropValue.setSkuId(sku.getSkuId());
            skuPropValue.setPropValueId(propValueId);
            skuPropValueService.save(skuPropValue);
            code=propValueId+"-";
        }
        sku.setQuickQueryCode(skuQuerycode);
        updateById(sku);


    }

    @Override
    public Result upsku(Integer skuId) {
        Sku sku = getById(skuId);
        if (sku.getSkuStatus().equals("ON_SALE")) {
            throw new LXLGException("商品已经上架，请勿重复操作", 401);
        }
        sku.setSkuStatus("ON_SALE");
        updateById(sku);
        return Result.getInstance().setCode(200).setMsg("商品上架成功");
    }

    @Override
    public Result downsku(Integer skuId) {
        Sku sku = getById(skuId);
        if (sku.getSkuStatus().equals("OFF_SALE")) {
            throw new LXLGException("商品已经下架，请勿重复操作", 402);
        }
        sku.setSkuStatus("OFF_SALE");
        updateById(sku);
        return Result.getInstance().setCode(200).setMsg("商品下架成功");
    }

    @Override
    public Result delsku(Integer skuId) {
        Sku sku = getById(skuId);
        if (sku.getSkuStatus().equals("ON_SALE")) {
            throw new LXLGException("请先下架商品，才能进行删除", 401);
        }
        if (sku.getSkuStatus().equals("DELETE")) {
            throw new LXLGException("商品已经删除，请勿重复操作", 403);
        }
        sku.setSkuStatus("DELETE");
        updateById(sku);
        return Result.getInstance().setCode(200).setMsg("商品删除成功");
    }

    /**
     * 增加销量
     *
     * @param skuId
     * @param count
     */
    @Override
    public void addSkuSalesCount(Integer skuId, Integer count) {
        Sku sku = getById(skuId);
        if (sku == null) {
            throw new LXLGException(ProductResultCode.SKU_INEXISTENCE);
        }
        sku.setSalesCount(sku.getSalesCount() + count);
        updateById(sku);
    }

    /**
     * 扣减数量
     * @param skuId
     * @param count
     */
    @Override
    public void subtractSkuSalesCount(Integer skuId, Integer count) {
        Sku sku = getById(skuId);
        if (sku == null) {
            throw new LXLGException(ProductResultCode.SKU_INEXISTENCE);
        }
        if((sku.getSalesCount() - count)<0){
            throw new LXLGException(ProductResultCode.SKU_SALESCOUNT_ERROR);
        }
        sku.setSalesCount(sku.getSalesCount() - count);
        updateById(sku);
    }

}
